package com.admin.common.security;

import com.admin.common.exception.UserCountLockException;
import com.admin.eneity.SysUser;
import com.admin.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;

/**
 * @author 吴驰明
 * @date 2023/7/14
 * @Description 自定义User Details
 */
@Service
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       SysUser sysUser= sysUserService.getByUsername(username);
       if (sysUser==null){
           throw new UsernameNotFoundException("用户名或者密码错误");
       }else if ("1".equals(sysUser.getStatus())){
           throw new UserCountLockException("该账号被封禁止 请联系管理员");
       }
        return new User(sysUser.getUsername(),sysUser.getPassword(),getUserAuthority(sysUser.getId()));
    }
    public List<GrantedAuthority> getUserAuthority(Long userId){
        String authority=sysUserService.getUserAuthorityInfo(userId);
        System.out.println("authority="+authority);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    };


}
